package controllers

import (
	"backend/common"
	"backend/models"
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/cloudwego/eino/schema"
	"github.com/gin-gonic/gin"
)

// ParseIntention 用户意图分析
func ParseIntention(ctx *gin.Context) {
	//准备消息
	mes := ctx.PostForm("intention")
	if len(mes) == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"status": "error", "message": "消息不能为空"})
		return
	}

	messages := []*schema.Message{
		schema.SystemMessage("你是一位专业的低代码平台项目分析师，擅长帮助用户分析项目需求并提供详细的功能规划，" +
			"用户将提供给你一段项目需求介绍，请你整理其中的关键信息，输出用户需求，并分解成各个功能并描述。" +
			"输出JSON格式:\n" +
			`{
  "intention": {
    "intention": "<项目需求概述，不超过10个字>",
    "func": [
      {
        "name": "<功能名，不超过10个字>",
        "description": "<功能描述>",
        "input": "<输入>",
        "output": "<输出>"
      }
    ],
    "language": "<编程语言，可以是简单应用（如C++、Java）、web应用（如vue、React）、或者前后端分离的项目（如React+Flask），如果用户没有指定，此项由你判断>"
  }
  "ok": <如果无法总结出有效信息，此项为false，并且其他项为空,否则为true>
}`),
		schema.UserMessage(mes),
	}

	//生成回复
	response, err := common.Interact(messages)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"status":  "error",
			"message": "服务器错误1 " + err.Error(),
		})
		return
	}

	//解析回复
	res := models.IntentionMessage{}
	err = json.Unmarshal([]byte(response.Content)[7:len(response.Content)-3], &res)

	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"status":  "error",
			"message": "服务器错误2 " + err.Error(),
		})
		return
	}

	if res.Ok == false {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"status":  "error",
			"message": "无效输入",
		})
	} else {
		userID, _ := getUserID(ctx)

		userIntention, err := createUserIntention(userID, res.Intention)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"status":  "error",
				"message": "无法保存用户意图",
			})
			return
		}
		//获取上面插入后的主键
		var id uint = userIntention.ID

		ctx.JSON(http.StatusOK, gin.H{
			"status":  "success",
			"message": "成功提取意图",
			"data": struct {
				Intention   models.Intention `json:"intention"`
				IntentionID uint             `json:"intentionID"`
			}{res.Intention, id},
		})
	}
}

// ChangeIntention 用户意图更改
func ChangeIntention(ctx *gin.Context) {
	// 解析请求
	mes := struct {
		Intention   models.Intention `json:"intention" binding:"required"`
		IntentionID uint             `json:"intentionID" binding:"required"`
	}{}
	err := ctx.ShouldBindJSON(&mes)
	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"status": "error", "message": "请确认请求格式1 " + err.Error()})
		return
	}

	intentionJS, err := json.MarshalIndent(mes.Intention, "", "  ")
	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"status": "error", "message": "请确认请求格式2 " + err.Error()})
		return
	}

	// TODO 更改意图到数据库
	userID, _ := getUserID(ctx)
	userIntention := &models.UserIntention{
		ID:        mes.IntentionID,
		UserID:    userID,
		Intention: mes.Intention.Intention,
		Request:   string(intentionJS),
	}
	err = updateUserIntention(userIntention)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "更新失败3 " + err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"status":  "success",
		"message": "成功更改意图",
	})
}

func GetIntention(ctx *gin.Context) {
	// 解析请求
	intentionIDS := ctx.Query("intentionID")
	intentionID, err := strconv.ParseUint(intentionIDS, 10, 64)

	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"status": "error", "message": "请确认请求格式" + err.Error()})
		return
	}

	intention, _ := getUserIntention(uint(intentionID))
	if intention == nil {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"status": "error", "message": "查询失败"})
		return
	}

	userID, _ := getUserID(ctx)
	if intention.UserID != userID {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"status": "error", "message": "没有权限"})
		return
	}

	intentionV := models.Intention{}
	err = json.Unmarshal([]byte(intention.Request), &intentionV)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "服务器错误"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"status":  "success",
		"message": "成功获取",
		"data": struct {
			Intention models.Intention `json:"intention"`
		}{intentionV},
	})
}

func DeleteIntention(ctx *gin.Context) {
	// 解析请求
	mes := struct {
		IntentionID uint `json:"intentionID" binding:"required"`
	}{}
	err := ctx.ShouldBindJSON(&mes)

	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"status": "error", "message": "请确认请求格式" + err.Error()})
		return
	}

	userID, _ := getUserID(ctx)
	err = deleteUserIntention(userID, uint(mes.IntentionID))
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"status":  "success",
		"message": "成功删除",
	})
}

func GetHistory(ctx *gin.Context) {
	userID, err := getUserID(ctx)
	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"status": "error", "message": err.Error()})
		return
	}

	history, err := getUserHistory(userID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"status":  "success",
		"message": "成功删除",
		"data": struct {
			History models.History `json:"history"`
		}{*history},
	})

}
